package com.apex.sdk.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ActivityChooserView;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.apex.bluetooth.callback.TitanMultiDetailCountCallback;
import com.apex.bluetooth.core.EABleManager;
import com.apex.bluetooth.enumeration.EABleConnectState;
import com.apex.bluetooth.model.TitanDataSyncType;
import com.apex.sdk.R;
import com.apex.sdk.databinding.ActivitySportDetailBinding;
import com.apex.sdk.dialog.WaitingDialog;
import com.apex.sdk.model.SportDetails;

import java.util.List;


public class TitanSportDetailActivity extends AppCompatActivity {
    private final String TAG = this.getClass().getSimpleName();
    private WaitingDialog waitingDialog;
    SportListAdapter sportListAdapter;
    List<SportDetails> ids;
    long sTime, eTime;
    private NotifyResultBroadcast notifyResultBroadcast;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x40) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
            } else if (msg.what == 0x41) {
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                Toast.makeText(TitanSportDetailActivity.this, getString(R.string.failed_to_get_data), Toast.LENGTH_SHORT).show();
            }
        }
    };
    final String NotifyDetailCount = "com.titan.detail.sync.count";
    final String NotifyResult = "com.titan.detail.sync.result";
    ActivitySportDetailBinding activitySportDetailBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activitySportDetailBinding=ActivitySportDetailBinding.inflate(getLayoutInflater());
        setContentView(activitySportDetailBinding.getRoot());
        activitySportDetailBinding.tool.setNavigationIcon(R.mipmap.exit_page);
        setSupportActionBar(activitySportDetailBinding.tool);
        getSupportActionBar().setTitle(null);
        activitySportDetailBinding.tool.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        String id = getIntent().getStringExtra("data");
        if (TextUtils.isEmpty(id) || "".equalsIgnoreCase(id)) {
            finish();
            return;
        } else {
            ids = JSONObject.parseArray(id, SportDetails.class);
        }
        if (ids == null || ids.isEmpty()) {
            finish();
            return;
        }
        notifyResultBroadcast = new NotifyResultBroadcast();
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            registerReceiver(notifyResultBroadcast, new IntentFilter(NotifyResult),Context.RECEIVER_EXPORTED);
        }else {
            registerReceiver(notifyResultBroadcast, new IntentFilter(NotifyResult));
        }
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        activitySportDetailBinding.sportList.setLayoutManager(linearLayoutManager);
        sportListAdapter = new SportListAdapter();
        activitySportDetailBinding.sportList.setAdapter(sportListAdapter);

    }

    class SportListAdapter extends RecyclerView.Adapter<SportListAdapter.SportView> {
        @NonNull
        @Override
        public SportView onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View childView = LayoutInflater.from(TitanSportDetailActivity.this).inflate(R.layout.adapter_sport_detail_item, parent, false);
            return new SportView(childView);
        }

        @Override
        public void onBindViewHolder(@NonNull SportView holder, int position) {
            if (ids == null) {
                return;
            }
            SportDetails sportDetails = ids.get(position);
            int id = sportDetails.getId();
            int type = sportDetails.getType();
            holder.idText.setText(id + "");
            if (type == 0) {
                holder.nameText.setText(getString(R.string.outdoor_walking));
            } else if (type == 1) {
                holder.nameText.setText(getString(R.string.outdoor_running));
            } else if (type == 2) {
                holder.nameText.setText(getString(R.string.outdoor_swimming));
            } else if (type == 3) {
                holder.nameText.setText(getString(R.string.outdoor_cycling));
            } else if (type == 4) {
                holder.nameText.setText(getString(R.string.outdoor_cross_country));
            } else if (type == 5) {
                holder.nameText.setText(getString(R.string.outdoor_hiking));
            } else if (type == 6) {
                holder.nameText.setText(getString(R.string.outdoor_mountaineering));
            } else if (type == 7) {
                holder.nameText.setText(getString(R.string.indoor_exercise));
            } else if (type == 8) {
                holder.nameText.setText(getString(R.string.indoor_walking));
            } else if (type == 9) {
                holder.nameText.setText(getString(R.string.indoor_running));
            } else if (type == 10) {
                holder.nameText.setText(getString(R.string.swimming));
            } else if (type == 11) {
                holder.nameText.setText(getString(R.string.indoor_cycling));
            } else if (type == 12) {
                holder.nameText.setText(getString(R.string.elliptical_machine));
            } else if (type == 13) {
                holder.nameText.setText(getString(R.string.rowing_machine));
            } else if (type == 14) {
                holder.nameText.setText(getString(R.string.yoga));
            }
            holder.getButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (EABleManager.getInstance().getDeviceConnectState() == EABleConnectState.STATE_CONNECTED) {
                        if (waitingDialog == null) {
                            waitingDialog = new WaitingDialog(TitanSportDetailActivity.this);
                        }
                        waitingDialog.show();
                        sTime = sportDetails.getStartTime();
                        eTime = sportDetails.getEndTime();
                        EABleManager.getInstance().syncTitanMultiSportDetailData(sportDetails.getId(), TitanDataSyncType.BEGIN, new TitanMultiDetailCountCallback() {
                            @Override
                            public void detailCount(int i) {
                                if (i <= 0) {
                                    if (mHandler != null) {
                                        mHandler.sendEmptyMessage(0x40);
                                    }
                                } else {
                                    Intent intent = new Intent(NotifyDetailCount);
                                    intent.putExtra("detailTotalCount", i);
                                    intent.putExtra("startTime", sTime);
                                    intent.putExtra("endTime", eTime);
                                    sendBroadcast(intent);
                                }
                            }

                            @Override
                            public void mutualFail(int i) {
                                if (mHandler != null) {
                                    mHandler.sendEmptyMessage(0x41);
                                }
                            }
                        });
                    }
                }
            });

        }

        @Override
        public int getItemCount() {
            return ids == null ? 0 : ids.size();
        }

        class SportView extends RecyclerView.ViewHolder {
            AppCompatButton getButton;
            TextView nameText;
            TextView idText;

            public SportView(@NonNull View itemView) {
                super(itemView);
                getButton = itemView.findViewById(R.id.get_detail);
                nameText = itemView.findViewById(R.id.sport_name);
                idText = itemView.findViewById(R.id.sport_id);
            }
        }
    }

    class NotifyResultBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (!TextUtils.isEmpty(action) && action.equalsIgnoreCase(NotifyResult)) {
                int resutlt = intent.getIntExtra("result", 0);
                if (waitingDialog != null) {
                    if (waitingDialog.isShowing()) {
                        waitingDialog.dismiss();
                    }
                }
                if (resutlt != 0) {
                    Log.e(TAG, "同步数据失败");
                    Toast.makeText(TitanSportDetailActivity.this, getString(R.string.failed_to_get_data), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }
        if (notifyResultBroadcast != null) {
            unregisterReceiver(notifyResultBroadcast);
            notifyResultBroadcast = null;
        }
        super.onDestroy();
    }
}
